document.addEventListener('DOMContentLoaded', function() {
  const changeButton = document.getElementById('changeContent');
  const resultDiv = document.getElementById('result');
  
  changeButton.addEventListener('click', async function() {
    const selectorType = document.getElementById('selectorType').value;
    const selectorValue = document.getElementById('selectorValue').value.trim();
    const newContent = document.getElementById('newContent').value;
    const replaceMode = document.getElementById('replaceMode').value;
    
    if (!selectorValue || !newContent) {
      showResult('请填写所有必填字段', 'error');
      return;
    }
    
    try {
      // 获取当前活动的标签页
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      
      // 构建选择器
      let selector;
      switch (selectorType) {
        case 'text':
          selector = `span:contains("${selectorValue}")`;
          break;
        case 'class':
          selector = `span.${selectorValue}`;
          break;
        case 'id':
          selector = `span#${selectorValue}`;
          break;
        case 'custom':
          selector = selectorValue;
          break;
        default:
          selector = selectorValue;
      }
      
      // 发送消息到content script
      const response = await chrome.tabs.sendMessage(tab.id, {
        action: 'changeSpanContent',
        selector: selector,
        newContent: newContent,
        replaceMode: replaceMode,
        originalSelector: selectorValue,
        selectorType: selectorType
      });
      
      if (response && response.success) {
        showResult(`成功更改了 ${response.changedCount} 个span元素`, 'success');
      } else {
        showResult(response?.message || '操作失败', 'error');
      }
    } catch (error) {
      showResult('执行出错: ' + error.message, 'error');
    }
  });
  
  function showResult(message, type) {
    resultDiv.textContent = message;
    resultDiv.className = 'result ' + type;
    resultDiv.style.display = 'block';
    
    setTimeout(() => {
      resultDiv.style.display = 'none';
    }, 3000);
  }
  
  // 根据选择器类型更新placeholder
  document.getElementById('selectorType').addEventListener('change', function() {
    const placeholderMap = {
      'text': '输入span元素的文本内容',
      'class': '输入CSS类名（不需要加点）',
      'id': '输入元素ID（不需要加#）',
      'custom': '输入任何有效的CSS选择器'
    };
    document.getElementById('selectorValue').placeholder = placeholderMap[this.value];
  });
});